package com.demo.common.dynamic.datasource.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.common.dynamic.datasource.constants.DataSourceNameConstants;
import com.demo.common.dynamic.datasource.entity.DataSourceConfig;
import com.demo.common.dynamic.datasource.mapper.DataSourceConfigMapper;
import com.demo.common.dynamic.datasource.service.DataSourceConfigService;
import com.demo.common.dynamic.datasource.utils.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 数据源配置
 *
 * @author molong
 * @since 2021/10/28
 */
@Service
@Slf4j
public class DataSourceConfigServiceImpl extends ServiceImpl<DataSourceConfigMapper, DataSourceConfig> implements DataSourceConfigService {

    @Override
    public void initDataSource() {
        List<DataSourceConfig> dbConfigs = this.list();
        if (!CollectionUtils.isEmpty(dbConfigs)) {
            for (DataSourceConfig dbConfig : dbConfigs) {
                //创建数据源
                createDataSource(dbConfig);
            }
        }
    }

    /**
     * 校验并初始化数据源
     *
     * @param dataSource 数据源
     */
    public void createDataSource(DataSourceConfig dataSource) {
        String dataSourceKey = DataSourceNameConstants.DATASOURCE_PREFIX + dataSource.getId();
        log.debug("初始化数据源：" + dataSourceKey);
        if (DynamicDataSource.getInstance().isExist(dataSourceKey)) {
            log.debug("数据源" + dataSourceKey + "之前已经创建");
        } else {
            String username = dataSource.getUsername();
            String password = dataSource.getPassword();
            String url = dataSource.getUrl();
            try {
                DynamicDataSource.getInstance().createDataSource(dataSourceKey, url, username, password);
            } catch (Exception e) {
                log.debug("数据源初始化失败:", e);
            }
        }

    }
}
